package com.hckj.jianzhijia;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.im.v2.AVIMClient;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.callback.AVIMClientCallback;
import com.avoscloud.leanchatlib.controller.ChatManager;
import com.avoscloud.leanchatlib.controller.ConversationEventHandler;
import com.hckj.jianzhijia.fragments.MainChatFragment;
import com.hckj.jianzhijia.fragments.MainCompanyFragment;
import com.hckj.jianzhijia.fragments.MainJobsFragment;
import com.hckj.jianzhijia.fragments.MainPushFragment;
import com.hckj.jianzhijia.model.CompanyUser;
import com.hckj.jianzhijia.model.VersionUpdate;
import com.hckj.jianzhijia.services.APKLoadingService;
import com.hckj.jianzhijia.utils.ExceptionUtils;
import com.hckj.jianzhijia.utils.MyActivityManager;
import com.hckj.jianzhijia.utils.SharedPreferencesUtil;
import com.hckj.jianzhijia.utils.ToastUtils;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 首页
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {


    @InjectView(R.id.frame_switch_content)
    FrameLayout frameSwitchContent;
    @InjectView(R.id.imgv_main_tab_jobs)
    ImageView imgvMainTabJobs;
    @InjectView(R.id.tv_main_tab_jobs)
    TextView tvMainTabJobs;
    @InjectView(R.id.imgv_main_tab_push)
    ImageView imgvMainTabPush;
    @InjectView(R.id.tv_main_tab_push)
    TextView tvMainTabPush;
    @InjectView(R.id.imgv_main_tab_chat)
    ImageView imgvMainTabChat;
    @InjectView(R.id.tv_main_tab_chat)
    TextView tvMainTabChat;
    @InjectView(R.id.imgv_main_tab_company)
    ImageView imgvMainTabCompany;
    @InjectView(R.id.tv_main_tab_company)
    TextView tvMainTabCompany;
    @InjectView(R.id.ll_navigationbar)
    LinearLayout llNavigationbar;
    @InjectView(R.id.rl_main_tab_jobs)
    RelativeLayout rlMainTabJobs;
    @InjectView(R.id.rl_main_tab_peoples)
    RelativeLayout rlMainTabPeoples;
    @InjectView(R.id.rl_main_tab_chat)
    RelativeLayout rlMainTabChat;
    @InjectView(R.id.rl_main_tab_company)
    RelativeLayout rlMainTabCompany;
    @InjectView(R.id.rl_parent)
    RelativeLayout rlParent;

    Drawable main_tab_chat_click;
    Drawable main_tab_chat_default;
    Drawable main_tab_company_click;
    Drawable main_tab_company_default;
    Drawable main_tab_jobs_click;
    Drawable main_tab_jobs_default;
    Drawable main_tab_peoples_click;
    Drawable main_tab_peoples_default;
    MainChatFragment mainChatFragment = null;
    MainPushFragment mainPeoplesFragment = null;
    MainCompanyFragment mainCompanyFragment = null;
    MainJobsFragment mainJobsFragment = null;

    private FragmentManager fragmentManager;
    private NotificationManager nm;
    private Notification notification;
    private VersionUpdate versionUpdate;
    private SharedPreferencesUtil sharedPreferencesUtil;

    public static final int CHOOSE_PHOTO = 123;
    public static final int GET_PHOTO = 124;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        fragmentManager = getSupportFragmentManager();
        sharedPreferencesUtil = new SharedPreferencesUtil(this);
        initData();
        initEvent();
        initChat();
        versionUpdate();
        mainJobsFragment = new MainJobsFragment();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.frame_switch_content, mainJobsFragment);
        fragmentTransaction.commit();
        imgvMainTabJobs.setImageDrawable(main_tab_jobs_click);
    }

    private void initChat() {
        CompanyUser temp = jianzhijiaApplacation.getCompanyUser();
        //String userId = temp.getName()+"#" + temp.getPhone();
        String userId = "123";
        System.out.println("userId" + userId);
        final ChatManager chatManager = ChatManager.getInstance();

        chatManager.init(this);
        if (!TextUtils.isEmpty(userId)) {
            chatManager.setupManagerWithUserId(userId);
        }
        chatManager.setConversationEventHandler(ConversationEventHandler.getInstance());
        ChatManager.getInstance().openClient(new AVIMClientCallback() {
            @Override
            public void done(AVIMClient avimClient, AVIMException e) {
                if (null == e) {

                } else {
                    ToastUtils.showToast(getApplicationContext(),"聊天功能开启失败");
                }
            }
        });
    }


    private void initEvent() {

        rlMainTabChat.setOnClickListener(this);
        rlMainTabCompany.setOnClickListener(this);
        rlMainTabJobs.setOnClickListener(this);
        rlMainTabPeoples.setOnClickListener(this);
    }

    private void initData() {

        main_tab_chat_click = getResources().getDrawable(R.drawable.main_tab_chat_click);
        main_tab_chat_default = getResources().getDrawable(R.drawable.main_tab_chat_default);
        main_tab_company_click = getResources().getDrawable(R.drawable.main_tab_company_click);
        main_tab_company_default = getResources().getDrawable(R.drawable.main_tab_company_default);
        main_tab_jobs_click = getResources().getDrawable(R.drawable.main_tab_jobs_click);
        main_tab_jobs_default = getResources().getDrawable(R.drawable.main_tab_jobs_default);
        main_tab_peoples_click = getResources().getDrawable(R.drawable.main_tab_peoples_click);
        main_tab_peoples_default = getResources().getDrawable(R.drawable.main_tab_peoples_default);

    }

    @Override
    public void onClick(View v) {
        int vId = v.getId();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        hideAllFragment(fragmentTransaction);
        imgvMainTabChat.setImageDrawable(main_tab_chat_default);
        imgvMainTabCompany.setImageDrawable(main_tab_company_default);
        imgvMainTabJobs.setImageDrawable(main_tab_jobs_default);
        imgvMainTabPush.setImageDrawable(main_tab_peoples_default);
        tvMainTabChat.setTextColor(getResources().getColor(R.color.main_tab_default_color));
        tvMainTabCompany.setTextColor(getResources().getColor(R.color.main_tab_default_color));
        tvMainTabJobs.setTextColor(getResources().getColor(R.color.main_tab_default_color));
        tvMainTabPush.setTextColor(getResources().getColor(R.color.main_tab_default_color));
        switch (vId) {
            case R.id.rl_main_tab_jobs:
                imgvMainTabJobs.setImageDrawable(main_tab_jobs_click);
                tvMainTabJobs.setTextColor(getResources().getColor(R.color.orange_text));
                if (mainJobsFragment != null) {
                    fragmentTransaction.show(mainJobsFragment);
                } else {
                    mainJobsFragment = new MainJobsFragment();
                    fragmentTransaction.add(R.id.frame_switch_content, mainJobsFragment);
                }
                break;

            case R.id.rl_main_tab_peoples:
                ToastUtils.showToast(getApplicationContext(),"正在开发中");
                imgvMainTabPush.setImageDrawable(main_tab_peoples_click);
                tvMainTabPush.setTextColor(getResources().getColor(R.color.orange_text));
                if (mainPeoplesFragment != null) {
                    fragmentTransaction.show(mainPeoplesFragment);
                } else {
                    mainPeoplesFragment = new MainPushFragment();
                    fragmentTransaction.add(R.id.frame_switch_content, mainPeoplesFragment);
                }
                break;

            case R.id.rl_main_tab_chat:
                imgvMainTabChat.setImageDrawable(main_tab_chat_click);
                tvMainTabChat.setTextColor(getResources().getColor(R.color.orange_text));
                if (mainChatFragment != null) {
                    fragmentTransaction.show(mainChatFragment);
                } else {
                    mainChatFragment = new MainChatFragment();
                    fragmentTransaction.add(R.id.frame_switch_content, mainChatFragment);
                }
                break;

            case R.id.rl_main_tab_company:
                imgvMainTabCompany.setImageDrawable(main_tab_company_click);
                tvMainTabCompany.setTextColor(getResources().getColor(R.color.orange_text));
                if (mainCompanyFragment != null) {
                    fragmentTransaction.show(mainCompanyFragment);
                } else {
                    mainCompanyFragment = MainCompanyFragment.newInstance(rlParent);
                    fragmentTransaction.add(R.id.frame_switch_content, mainCompanyFragment);
                }
                break;
        }
        fragmentTransaction.commit();
    }

    private void hideAllFragment(FragmentTransaction fragmentTransaction) {
        if (mainCompanyFragment != null && !mainCompanyFragment.isHidden()) {
            fragmentTransaction.hide(mainCompanyFragment);
        }
        if (mainChatFragment != null && !mainChatFragment.isHidden()) {
            fragmentTransaction.hide(mainChatFragment);
        }
        if (mainPeoplesFragment != null && !mainPeoplesFragment.isHidden()) {
            fragmentTransaction.hide(mainPeoplesFragment);
        }
        if (mainJobsFragment != null && !mainJobsFragment.isHidden()) {
            fragmentTransaction.hide(mainJobsFragment);
        }
    }


    @Override
    public void onBackPressed() {
        Dialog.Builder builder = null;

        builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                MyActivityManager.getInstance().AppExit(getApplicationContext());
                super.onPositiveActionClicked(fragment);
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {

                super.onNegativeActionClicked(fragment);
            }
        };

        ((SimpleDialog.Builder) builder).message("是否确认退出")
                    .positiveAction("确认")
                    .negativeAction("取消");
        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.show(getSupportFragmentManager(), null);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void showNotification() {
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notification = new Notification.Builder(this)
                                   .setSmallIcon(R.mipmap.ic_launcher)
                                   .setContentTitle("兼职家更新中...")// 设置在下拉status// bar后Activity，本例子中的NotififyMessage的TextView中显示的标题
                                   .setProgress(100, 0, false)
                                   .getNotification();
        notification.flags |= Notification.FLAG_NO_CLEAR;
        nm.notify(0, notification);
    }


    private void versionUpdate() {

        if(!sharedPreferencesUtil.ifAutoUpdate()){
            return ;
        }
        PackageInfo info = null;
        try {
            info = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        // 当前版本的版本号
        AVQuery<AVObject> query = new AVQuery<AVObject>("VersionUpdate");
        query.whereEqualTo("clientType", 0);
        query.orderByDescending("versionCode");
        query.whereGreaterThan("versionCode", info.versionCode);

        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    if (list.size() != 0) {
                        versionUpdate = new VersionUpdate(list.get(0));
                        Dialog.Builder builder = null;
                        builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
                            @Override
                            public void onPositiveActionClicked(DialogFragment fragment) {

                                if(versionUpdate.getAPK() == null){
                                    ToastUtils.showToast(getApplicationContext(),"更新失败");
                                    fragment.dismiss();
                                    return ;
                                }
                                APKLoadingService.startUpdate(MainActivity.this, versionUpdate.getAPK().getUrl());
                                super.onPositiveActionClicked(fragment);
                            }

                            @Override
                            public void onNegativeActionClicked(DialogFragment fragment) {
                                fragment.dismiss();
                                super.onNegativeActionClicked(fragment);
                            }
                        };

                        ((SimpleDialog.Builder) builder).message("更新内容：" + versionUpdate.getVersionDescribe())
                                    .positiveAction("确认")
                                    .negativeAction("取消").title("更新");
                        DialogFragment fragment = DialogFragment.newInstance(builder);
                        fragment.show(getSupportFragmentManager(), null);

                    }
                } else {
                    ToastUtils.showToast(getApplicationContext(), "获取更新信息失败 " + ExceptionUtils.getExceptionInfo(e));
                }
            }
        });


    }

}
